package com.example.onenetdht11;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.example.onenetdht11.dao.UserDao2;
import com.example.onenetdht11.entity.User2;
import com.example.onenetdht11.util.OneNetUtils;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class ListFragment extends Fragment {
    View view;
    ClockView cvtemp,cvhumi;
    TextView tvsmoke,tvsound;
    EditText numLimitation,numMaxtemp;
    Button btnopen,btnclose;
    Spinner spdargee;
    User2 user;
    UserDao2 userDao;
    MainActivity ma;
    OneNetUtils utils;
    private ArrayList<String> numberlist = new ArrayList<>();
    private String selectMaxText = "";
    private String selectMinText = "";

    public ListFragment(){

    }
    public ListFragment(MainActivity mainActivity, User2 user,OneNetUtils utils){
        this.ma = mainActivity;
        this.user = user;
        this.utils = utils;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_list,container,false);//第一个参数是布局文件名，第二个是父容器
        initView();
        initData();
        initListener();
        return view;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            initData();
        }
    }


    @Override
    public void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }
    void initView(){
        cvtemp = view.findViewById(R.id.cv_temp);
        cvhumi = view.findViewById(R.id.cv_humi);
        tvsmoke = view.findViewById(R.id.tv_smoke);
        tvsound = view.findViewById(R.id.tv_sound);
        spdargee = view.findViewById(R.id.sp_dargee);
        btnopen = view.findViewById(R.id.btn_open);
        btnclose = view.findViewById(R.id.btn_close);

        numLimitation = view.findViewById(R.id.num_limitation);
        numLimitation.setInputType(InputType.TYPE_NULL);
        numMaxtemp = view.findViewById(R.id.num_maxtemp);
        numMaxtemp.setInputType(InputType.TYPE_NULL);
    }
    String[] spData = {"30°","60°","90°"};
    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    void initData() {
        ArrayAdapter<String> adapter =new ArrayAdapter<>(ma,
                android.R.layout.simple_spinner_dropdown_item, spData);
        spdargee.setAdapter(adapter);

        numberlist.clear();
        for (int i = -30; i <= 70; i++) {
            numberlist.add(String.format("%d", i));
        }
        if (user.getMintmp() == null || user.getMintmp().equals("")){
            numLimitation.setText("20");
        }else
            numLimitation.setText(user.getMintmp());
        if (user.getMaxtmp() == null || user.getMaxtmp().equals("")){
            numMaxtemp.setText("25");
        }else
            numMaxtemp.setText(user.getMaxtmp());
        updateTime();
    }
    void initListener(){
        View.OnClickListener listener = new View.OnClickListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.num_limitation:
                        if (user.getMintmp() == null || user.getMintmp().equals("")){
                            showMinDialog(numLimitation, numberlist, 20 + 30);
                        }else
                            showMinDialog(numLimitation, numberlist, Integer.parseInt(user.getMintmp())+30);
                        break;
                    case R.id.num_maxtemp:
                        if (user.getMaxtmp() == null || user.getMaxtmp().equals("")){
                            showMaxDialog(numMaxtemp, numberlist, 25 + 30);
                        }else
                            showMaxDialog(numMaxtemp, numberlist, Integer.parseInt(user.getMaxtmp())+30);
                        break;
                    case R.id.btn_open:
                        sendCmd(Contests.FORWARD);
                        break;
                    case R.id.btn_close:
                        sendCmd(Contests.BACKWARD);
                        break;
                }
            }
        };

        numLimitation.setOnClickListener(listener);
        numMaxtemp.setOnClickListener(listener);
        btnopen.setOnClickListener(listener);
        btnclose.setOnClickListener(listener);
        spdargee.setOnItemSelectedListener(onItemSelectedListener);
    }
    AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String dragee = parent.getItemAtPosition(position).toString();
            switch (dragee) {
                case "30°":
                    Contests.DRAGEE = "30";
                    break;
                case "60°":
                    Contests.DRAGEE = "60";
                    break;
                case "90°":
                    Contests.DRAGEE = "90";
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Contests.DRAGEE = "30°";
        }
    };
    private void showMaxDialog(TextView textView, ArrayList<String> list, int selected){
        showMaxChoiceDialog(list, textView, selected,
                new WheelView.OnWheelViewListener() {
                    @Override
                    public void onSelected(int selectedIndex, String item) {
                        selectMaxText = item;
                    }
                });
    }

    private void showMinDialog(TextView textView, ArrayList<String> list, int selected){
        showMinChoiceDialog(list, textView, selected,
                new WheelView.OnWheelViewListener() {
                    @Override
                    public void onSelected(int selectedIndex, String item) {
                        selectMinText = item;
                    }
                });
    }

    private final Timer timer=new Timer();
    void updateTime(){
        timer.schedule(new TimerTask() {
            class runOnUiThread {
                public runOnUiThread(Runnable runnable) {
                    runnable.run();
                }
            }

            @Override
            public void run() {
                new runOnUiThread(runnable);
 //               new Thread(runnable).start();
            }
        },0,6000);
    }

    private void showMaxChoiceDialog(ArrayList<String> dataList,final TextView textView,int selected,
                                  WheelView.OnWheelViewListener listener){
        View outerView = LayoutInflater.from(ma).inflate(R.layout.dialog_wheelview,null);
        final WheelView wheelView = outerView.findViewById(R.id.wheel_view);
        wheelView.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelView.setItems(dataList);// 设置数据源
        wheelView.setSeletion(selected);// 默认选中第三项
        wheelView.setOnWheelViewListener(listener);

        // 显示对话框，点击确认后将所选项的值显示到Button上
        AlertDialog alertDialog = new AlertDialog.Builder(ma)
                .setView(outerView)
                .setPositiveButton("确认",
                        (dialogInterface, i) -> {
                            textView.setText(selectMaxText);
//                            new Thread(updateMaxTemp).start();
                            user.setMaxtmp(selectMaxText);
                            userDao = new UserDao2(this.ma);
                            userDao.updateMaxTempById(user);
                            textView.setTextColor(this.getResources().getColor(R.color.black));
                            Contests.MaxTemp = user.getMaxtmp();
                        })
                .setNegativeButton("取消",null).create();
        alertDialog.show();
        int green = this.getResources().getColor(R.color.black);
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(green);
        alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(green);
    }
    private void showMinChoiceDialog(ArrayList<String> dataList,final TextView textView,int selected,
                                     WheelView.OnWheelViewListener listener){
        View outerView = LayoutInflater.from(ma).inflate(R.layout.dialog_wheelview,null);
        final WheelView wheelView = outerView.findViewById(R.id.wheel_view);
        wheelView.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelView.setItems(dataList);// 设置数据源
        wheelView.setSeletion(selected);// 默认选中第三项
        wheelView.setOnWheelViewListener(listener);

        // 显示对话框，点击确认后将所选项的值显示到Button上
        AlertDialog alertDialog = new AlertDialog.Builder(ma)
                .setView(outerView)
                .setPositiveButton("确认",
                        (dialogInterface, i) -> {
                            textView.setText(selectMinText);
//                            new Thread(updatemintemp).start();
                            user.setMintmp(selectMinText);
                            userDao = new UserDao2(this.ma);
                            userDao.updateMinTempById(user);
                            textView.setTextColor(this.getResources().getColor(R.color.black));
                            Contests.MinTemp = user.getMintmp();
                        })
                .setNegativeButton("取消",null).create();
        alertDialog.show();
        int green = this.getResources().getColor(R.color.black);
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(green);
        alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(green);
    }

        Runnable runnable = new Runnable() {
        @SuppressLint("NewApi")
        @Override
        public void run() {
            if (Looper.myLooper() == null) {
                Looper.prepare();
                System.out.println("数据获取" + utils.getInfo(Contests.WDStream));
                if (utils.getInfo(Contests.WDStream)!= null && !utils.getInfo(Contests.WDStream).equals("")){
                    cvtemp.setCompleteDegree(Float.parseFloat(utils.getInfo(Contests.WDStream)));
                }
                else
                    cvtemp.setCompleteDegree(0);
                if (utils.getInfo(Contests.SDStream)!= null && !utils.getInfo(Contests.SDStream).equals(""))
                    cvhumi.setCompleteDegree(Float.parseFloat(utils.getInfo(Contests.SDStream)));
                else
                    cvhumi.setCompleteDegree(0);
                tvsmoke.setText(utils.getInfo(Contests.MQStream));
                tvsound.setText(utils.getInfo(Contests.SoundStream));
                Looper.loop();
            } else {
                Looper.prepare();
                cvtemp.setCompleteDegree(Float.parseFloat(utils.getInfo(Contests.WDStream)));
                cvhumi.setCompleteDegree(Float.parseFloat(utils.getInfo(Contests.SDStream)));
                tvsmoke.setText(utils.getInfo(Contests.MQStream));
                Looper.loop();
            }
        }
    };

/*    Runnable updatemintemp = new Runnable() {
        @Override
        public void run() {
            userDao.updatemintemp(Contests.id,selectMinText);
        }
    };

    Runnable updateMaxTemp = new Runnable() {
        @Override
        public void run() {
            userDao.updatemaxtemp(Contests.id,selectMaxText);
        }
    };*/
    public void sendCmd(int no){
        if (no == Contests.FORWARD){
            new PostCmdThread(Contests.forward+Contests.DRAGEE).start();
        }else if (no == Contests.BACKWARD){
            new PostCmdThread(Contests.backward+Contests.DRAGEE).start();
        }else if (no == Contests.STOP){
            new PostCmdThread(Contests.stop).start();
        }
    }

    class PostCmdThread extends Thread{
        String cmd;

        public PostCmdThread(String cmd){
            this.cmd = cmd;
        }
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void run() {
            Looper.prepare();
            utils.postCmd(this.cmd);
            Looper.loop();
        }
    }
}
